﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;

namespace PasswordChange
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                var principalContext = new PrincipalContext(ContextType.Domain);
                var userPrincipal = UserPrincipal.FindByIdentity(principalContext, txtUsername.Text);

                if (userPrincipal == null) throw new Exception("User principal was not found");

                userPrincipal.ChangePassword(txtOldPass.Text, txtNewPass.Text);
                userPrincipal.Save();
                MessageBox.Show("Password changed successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error:\n Your password must be at least 4 characters and have not been used for your last 3 passwords.");
            }

        }

        private void txtNewPass_TextChanged(object sender, EventArgs e)
        {
            btnSubmit.Enabled = (txtNewPassAgain.Text == txtNewPass.Text);
        }

        private void txtNewPassAgain_TextChanged(object sender, EventArgs e)
        {
            btnSubmit.Enabled = (txtNewPassAgain.Text == txtNewPass.Text);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form1.ActiveForm.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtUsername.Text = Environment.UserName;
        }
    }
}
